import React from 'react';
import { connect } from 'dva';
import { Button, Table, Form, Input, Popconfirm, DatePicker, Select, TreeSelect, } from 'antd';
import AddBorrowModal from '../../components/borrow/AddBorrowModal';
import SecondBorrowModal from '../../components/borrow/SecondBorrowModal';
import AddBorrowDetailModal from '../../components/borrow/AddBorrowDetailModal';
import BorrowReturnModal from '../../components/borrow/BorrowReturnModal';
import RemarkModal from '../../components/borrow/RemarkModal'
import BorrowReturnDetailModal from '../../components/borrow/BorrowReturnDetailModal'
const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const RangePicker = DatePicker.RangePicker;

function Borrow({ dispatch, borrow, loading, form }) {

    const { getFieldDecorator, getFieldsValue, getFieldValue } = form;
    const { modalVisible, assetList, name, modalType, detailList, editDetailList } = borrow


    const columns = [{
        title: '单号',
        dataIndex: 'id_',
        key: 'id_',
        width: 150,
    },
    {
        title: '预计执行时间',
        dataIndex: 'executeTime',
        key: 'executeTime',
        width: 150,
    }, {
        title: '指定操作人',
        dataIndex: 'userName',
        key: 'userName',
        width: 150,
    },
    // {
    //     title: '备注',
    //     dataIndex: 'remark',
    //     key: 'remark',
    //     width: 200,
    // },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
        render: (value, row, index) => {
            return (
                value == 1 ? "待处理" : value == 2 ? "待归还" : value == 3 ? "已完成" : ''
            )
        }
    }, {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 150,
    }, {
        title: '创建人',
        dataIndex: 'createAccount',
        key: 'createAccount',
        width: 100,
    }, {
        title: '操作',
        key: 'operation',
        width: 100,
        render: (text, record) => (
            <span>
                {(record.status == 1) ? (
                    <span>
                        {/* <a onClick={onEditItem.bind(null, record.id_)}>编辑</a> */}
                        <a onClick={onBorrow.bind(null, record.id_)}>确认借用</a>
                        <span className="ant-divider" />
                        <Popconfirm title="确认删除？" onConfirm={deleteHandler.bind(null, record.id_)}>
                            <a>删除</a>
                        </Popconfirm>
                        <span className="ant-divider" />
                    </span>
                ) : (record.status == 2) ? (
                    <span>
                        <a onClick={onReturn.bind(null, record.id_)}>归还</a>
                        <span className="ant-divider" />
                    </span>
                ) : ''}
                <a onClick={onViewItem.bind(null, record.id_)}>查看</a>
            </span>
        ),
    }];

    const pagination = {
        current: borrow.current,
        pageSize: borrow.currentSize,
        total: borrow.total,
        showSizeChanger: true,
        showTotal: (total => '共' + borrow.total + '条'),
        onShowSizeChange(current, size) {
            dispatch({
                type: 'borrow/queryList',
                payload: { ...getFieldsValue(), ...{ 'pageNum': current, 'pageSize': size } },
            });
        },
        onChange(current) {
            dispatch({
                type: 'borrow/queryList',
                payload: { ...getFieldsValue(), ...{ 'pageNum': current, 'pageSize': borrow.currentSize } },
            });
        },
    };
    const addHandler = () => {
        dispatch({
            type: 'borrow/onAddViewItem',
            payload: {
                modalType: 'create',
            },
        })
    }

    function deleteHandler(id) {
        dispatch({
            type: 'borrow/remove',
            payload: { id, search: { ...getFieldsValue() } },
        });
    }

    const onBorrow = (id) => {
        dispatch({
            type: 'borrow/onBorrowReturnViewItem',
            payload: { id: id, modalType: 'updateToBorrow' }
        })
    }

    const onReturn = (id) => {
        dispatch({
            type: 'borrow/onReturnViewItem',
            payload: { id: id, modalType: 'updateToReturn' }
        })
    }

    const onEditItem = (id) => {
        dispatch({
            type: 'borrow/qryById',
            payload: id,
        })
    }

    const submitHandle = () => {
        dispatch({
            type: 'borrow/queryList',
            payload: { ...getFieldsValue() },
        });
    }

    function handleClear() {
        form.resetFields();
    }
    const onViewItem = (id) => {
        dispatch({
            type: 'borrow/onViewItem',
            payload: id,
        })
    }

    const addBorrowModalProps = {
        item: borrow.currentItem,
        visible: modalVisible,
        type: modalType,
        maskClosable: false,
        dispatch: dispatch,
        id: borrow.borrowId,
        userList: borrow.userList,
        roomList: borrow.roomList,
        assetBrandList: borrow.assetBrandList,
        confirmLoading: loading,
        borrowReturnDetail: borrow.detailList,
        title: `新增借用单`,
        wrapClassName: 'vertical-center-modal',
        newKey: borrow.newKey,
        dispatch: dispatch,
        onOk(data) {
            dispatch({
                type: `borrow/create`,
                payload: data,
            })
        },
        onCancel() {
            dispatch({
                type: 'borrow/hideModal',
            })
        },
    }

    const secondModalProps = {
        item: borrow.qryAssetItem,
        visible: borrow.secondModalVisible,
        assetList: assetList,
        userList: borrow.userList,
        assetType: borrow.assetTypeTree,
        detailList: detailList,
        roomList: borrow.roomList,
        assetBrandList: borrow.assetBrandList,
        assetModelList:borrow.assetModelList,
        rackList: borrow.rackList,
        assetCurrent: borrow.assetCurrent,
        assetCurrentSize: borrow.assetCurrentSize,
        assetTotal: borrow.assetTotal,
        maskClosable: false,
        dispatch: dispatch,
        confirmLoading: loading,
        title: '新增明细',
        wrapClassName: 'vertical-center-modal',
        newKey: borrow.newKey,
        onCancel() {
            dispatch({
                type: 'borrow/hideSecondModal',
            })
        },

        addDetailHandler(detailList) {
            dispatch({
                type: 'borrow/changeDetailList',
                payload: detailList,
            });
        },

        searchHandle(data) {
            dispatch({
                type: 'borrow/querAssetListByParam',
                payload: data,
            });
        }
    }

    const addBorrowDetailModal = {
        item: borrow.assetItem,
        visible: borrow.addBorrowDetailModalVisible,
        // form: form,
        deptList: borrow.deptList,
        deptUserList: borrow.deptUserList,
        maskClosable: false,
        confirmLoading: loading,
        title: '添加借用详情',
        wrapClassName: 'vertical-center-modal',
        newKey: borrow.newKey,
        dispatch: dispatch,
        onCancel() {
            dispatch({
                type: 'borrow/hideAddBorrowDetailModal',
            })
        },

        // 添加详情处理
        addBorrowDetailHandler(data) {
            for (var i = 0; i < borrow.detailList.length; i++) {
                if (data.assetId == borrow.detailList[i].assetId_) {
                    borrow.detailList[i].borrowType = data.borrowType;
                    borrow.detailList[i].targetManageBranchId = data.targetManageBranch;

                    getDeptName(borrow.deptList, data.targetManageBranch);
                    borrow.detailList[i].targetManageBranchName = borrow.name;

                    borrow.detailList[i].targetUseBranchId = data.targetUseBranch;

                    getDeptName(borrow.deptList, data.targetUseBranch);
                    borrow.detailList[i].targetUseBranchName = borrow.name;

                    borrow.detailList[i].targetEndUser = data.targetEndUser;
                    borrow.detailList[i].targetEndUserName = getUser(data.targetEndUser);
                    borrow.detailList[i].returnRemark = data.returnRemark;

                    // 回显信息
                    borrow.detailList[i].manageBranchId_ = data.targetManageBranch;
                    borrow.detailList[i].useBranchId_ = data.targetUseBranch;
                    borrow.detailList[i].endUser = data.targetEndUser;
                }
            }
            dispatch({
                type: 'borrow/updateAddDetaiList',
                payload: borrow.detailList,
            })
        }
    }
    const getUser = (id) => {
        for (var i in borrow.deptUserList) {
            if (id == borrow.deptUserList[i].id_) {
                return borrow.deptUserList[i].name;
            }
        }
    }

    const getDeptName = (data, id) => {
        for (var i in data) {
            if (data[i].id_ == id) {
                borrow.name = data[i].name;
                return;
            } else {
                getDeptName(data[i].depts, id);
            }
        }
    }

    const borrowReturnModal = {
        item: borrow.borrowReturnViewItem,
        visible: borrow.borrowReturnModalVisible,
        type: modalType,
        maskClosable: false,
        borrowReturnDetailList: borrow.borrowReturnDetailList,
        confirmLoading: loading,
        title: `${modalType === 'updateToBorrow' ? `借用` : modalType === 'updateToReturn' ? '归还' : ''}`,
        wrapClassName: 'vertical-center-modal',
        newKey: borrow.newKey,
        onOk(data) {
            dispatch({
                type: `borrow/${modalType}`,
                payload: data,
            })
        },
        onCancel() {
            dispatch({
                type: 'borrow/hideBorrowReturnViewModal',
            })
        },
        onEditRemark(data) {
            dispatch({
                type: 'borrow/queryDetailById',
                payload: data,
            })
        },
    }

    const remarkModal = {
        item: borrow.currentItem,
        visible: borrow.remarkModalVisible,
        maskClosable: false,
        confirmLoading: loading,
        title: `编辑备注`,
        wrapClassName: 'vertical-center-modal',
        newKey: borrow.newKey,
        onOk(data) {
            for (var i = 0; i < borrow.borrowReturnDetailList.length; i++) {
                if (data.borrowReturnDetailId == borrow.borrowReturnDetailList[i].id_) {
                    borrow.borrowReturnDetailList[i].returnRemark = data.returnRemark;
                }
            }
            dispatch({
                type: `borrow/updateBorrowReturnDetailList`,
                payload: borrow.borrowReturnDetailList,
            })
        },
        onCancel() {
            dispatch({
                type: 'borrow/hideRemarkViewModal',
            })
        },
    }

    const viewModalProps = {
        item: borrow.viewItem,
        visible: borrow.viewModalVisible,
        // form: form,
        maskClosable: false,
        confirmLoading: loading,
        title: '查看',
        wrapClassName: 'vertical-center-modal',
        newKey: borrow.newKey,
        onCancel() {
            dispatch({
                type: 'borrow/hideViewModal',
            })
        }
    }

    return (
        <div style={{ backgroundColor: '#fff' }}>
            <div style={{ minHeight: '100%' }}>
                <div style={{ width: '100%', backgroundColor: '#fff', lineHeight: '40px', paddingLeft: '20px', paddingTop: '10px' }}>
                    <Form layout="inline" >
                        <FormItem>
                            {getFieldDecorator('userName')(
                                <Input type="text" placeholder="操作人" style={{ width: '200px' }} />
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('executeTime')(
                                <RangePicker style={{ width: '300px' }} format="YYYY-MM-DD" />
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('status')(
                                <Select
                                    showSearch
                                    style={{ width: 200 }}
                                    placeholder="选择状态"
                                    optionFilterProp="children"
                                >
                                    <Option value="">全部</Option>
                                    <Option value="1">待处理</Option>
                                    <Option value="2">待归还</Option>
                                    <Option value="3">已完成</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem>
                            <Button type="primary" size='large' onClick={submitHandle} className='ant-search-btn'>查询</Button>
                        </FormItem>
                        <FormItem>
                            <Button size="large" htmlType="reset" onClick={handleClear}>清空</Button>
                        </FormItem>

                        <div style={{ marginTop: '-40px', textAlign: 'right', paddingRight: '10px' }}>
                            <FormItem>
                                <Button type="primary" size='large' onClick={addHandler}>新增借用单</Button>
                            </FormItem>
                        </div>
                    </Form>
                </div>

                <div style={{ width: '100%', padding: "30px 20px", }}>
                    <Table columns={columns} rowKey={record => record.id_} loading={loading} dataSource={borrow.borrowList} pagination={pagination}
                    />
                </div>
                <AddBorrowModal {...addBorrowModalProps} />
                <SecondBorrowModal {...secondModalProps} />
                <AddBorrowDetailModal {...addBorrowDetailModal} />
                <BorrowReturnModal {...borrowReturnModal} />
                <RemarkModal {...remarkModal} />
                <BorrowReturnDetailModal {...viewModalProps} />

            </div>
        </div>
    );
}

function mapStateToProps(state) {
    return { borrow: state.borrow, loading: state.loading.models.borrow };
}

Borrow = Form.create()(Borrow);

export default connect(mapStateToProps)(Borrow);